import React, { Component } from 'react';
import "./user.scss"
import { getApiUserInfo , getApiUpload , getApiProfile , getApiCompenyList , getApiresetpwd , getApiChangeMobile , getApiSend } from "../../axios/api"
import { message } from "antd"
import { get , set , remove } from '../../axios/localstorage';
import { connect } from 'react-redux'
import { changeUserInfo } from '../../redux/action';

class user extends Component {

    state = {
        type:1,
        name:'',
        mailbox:'',
        showIdArr:false,

        msg:'',
        showMsg:false,
        phone:'',
        code:'',
        password:'',
        confirmpassword:'',

        ischangePas:false,
        ischangePhone:false,

        success:false,

        vipLevel:0,
        showVipRule:false,

        rule:'<p>1、普通会员： 认证后即可成为普通会员</p>',
        isSend:false,
        countDownNum:60,
        data:{

        },
        avatar:'',
        avatarUrl:'',
        managerData:{

        },
        companyList:[],
        showCompany:false,
        company:"",
        
    }

    componentWillMount(){
        window.scroll(0,0);
        
        this.getUserInfo();

        getApiCompenyList({
            type:get('type')?get('type'):0,
            content:get('city')?get('city'):get('mechanism'),
        })
        .then( req =>{
            if(req.data.code === 1){
                let data = req.data.data;
                this.setState({
                    companyList:data
                })
            }
        }).catch( err =>{
            console.error(err);
        })

    }

    getManager=()=>{
        // let param = {
        //     token:get('token')
        // }

        // getApiAccountManager(param)
        // .then( req =>{
        //     console.log(req.data);
        //     if(req.data.code === 1){
        //         this.setState({
        //             managerData:req.data.data.account_manager
        //         })
        //     }
        // }).catch( err =>{
        //     console.error(err);
        // })
    }

    saveUserInfo=()=>{
        let param = {
            token:get('token'),
            type:get('type')?get('type'):0,
            content:get('city')?get('city'):get('mechanism'),
        }

        getApiUserInfo(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){

                let data = req.data.data;
    
                set('userinfo',data);
            }
        }).catch( err =>{
            console.error(err)
        })
    }

    gotoUpdateInfo=()=>{
        // window.location.reload();

        // let param = this.state.data;
        // param.token = get('token');
        

        let param = {
            token:get('token'),
            nickname:this.state.data.nickname,
            truename:this.state.data.truename,
            email:this.state.data.email,
            s_number:this.state.data.s_number, 
            company:this.state.data.company, 
            type:get('type')?get('type'):0,
            content:get('city')?get('city'):get('mechanism'),
            
        }

        if(this.state.avatarUrl){
            param.avatar = this.state.avatarUrl;
        }




        getApiProfile(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){

                let data = get('userinfo');

                message.success('更新成功！');

                if(data.nickname !== param.nickname){

                    console.log(123);

                    data.nickname = param.nickname;
                    this.saveUserInfo();
                    const { dispatch , info } = this.props;
                    dispatch(changeUserInfo(!info));
                    return false;
                }


                if(data.avatar !== this.state.avatarUrl){
                    data.avatar_text = this.state.avatarUrl;
                    this.saveUserInfo();
                    const { dispatch , info } = this.props;
                    dispatch(changeUserInfo(!info));
                    return false;
                    // window.location.reload();
                }

                
                
            }else{
                message.info(req.data.msg);
            }
        }).catch( err =>{
            console.error(err);
        })

    }

    componentDidMount(){

    }

    getUserInfo=()=>{
        let param = {
            token:get('token'),
            type:get('type')?get('type'):0,
            content:get('city')?get('city'):get('mechanism'),
        }

        getApiUserInfo(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){

                let data = req.data.data;
    
                this.setState({
                    data,
                    avatar:data.avatar_text
                })
            }
        }).catch( err =>{
            console.error(err)
        })
    }

    gotoUpdatePsw=()=>{
        if(!this.state.phone){
            this.setState({
                msg:'请先输入手机号！',
                showMsg:true
            })
            return false;
        }

        var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;

        if (!myreg.test(this.state.phone)) {
            this.setState({
                msg:'请输入准确的手机号码！',
                showMsg:true
            })
            return false;
        }

        if(!this.state.code){
            this.setState({
                msg:'请先输入验证码！',
                showMsg:true
            })
            return false;
        }

        if(!this.state.password){
            this.setState({
                msg:'请先输入新密码！',
                showMsg:true
            })
            return false;
        }

        if(!this.state.confirmpassword){
            this.setState({
                msg:'请确认新密码！',
                showMsg:true
            })
            return false;
        }

        if(this.state.password !== this.state.confirmpassword){
            this.setState({
                msg:'两次输入不一致！',
                showMsg:true
            })
            return false;
        }



        let param = {
            type:"mobile",
            mobile:this.state.phone,
            captcha:this.state.code,
            newpassword:this.state.password,
            types:get('type')?get('type'):0,
            // content:get('city')?get('city'):get('mechanism'),
        }

        getApiresetpwd(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){
                message.success("密码修改成功！")
                this.setState({
                    success:true
                })
                // remove('token');

                setTimeout(()=>{
                    remove('token');
                    this.props.history.push('/login');
                },3000)
            }else{
                this.setState({
                    showMsg:true,
                    msg:req.data.msg,
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    gotoLoadImg=(event)=>{
        let file = event.target.files[0];

        console.log(file);

        let fd = new FormData()
    
        fd.append('file', file);
        fd.append('token', get('token'));
        fd.append('type',2);

        getApiUpload(fd)
        .then( req =>{
            console.log(req.data);
            if(req.data.code === 1){
                let data = req.data.data;
                this.setState({
                    avatar:data.fullurl,
                    avatarUrl:data.url
                })
            }
        }).catch( err =>{
            console.error(err)
        })

    }

    gotoChooseId=(item)=>{
        let data = this.state.data;
        data.type = item.type
        this.setState({
            idname:item.name,
            data
        })
    }

    gotoClose=()=>{
        this.setState({
            phone:'',
            code:'',
            password:'',
            confirmpassword:'',
            ischangePas:false,
            ischangePhone:false,
            success:false,
            showMsg:false,
        })
    }

    gotoPage=(page)=>{
        this.props.history.push(page);
    }

    countDown=() =>{ 
        let countDownNum = this.state.countDownNum-1;//获取倒计时初始值
        //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
        this.timer = setInterval(() => {


            if(countDownNum<=0){
                clearInterval(this.timer);
                this.setState({ countDownNum:60,  isSend: false })
            }else{
                this.setState({
                    countDownNum:(countDownNum--)
                })
            }
        }, 1000);
    }

    changeName=(event)=>{
        let data = this.state.data;
        data.nickname = event.target.value;
        this.setState({
            data
        })
    }

    changeEmail=(event)=>{
        let data = this.state.data;
        data.email = event.target.value;
        this.setState({
            data
        })
    }

    changeDataStr=(event,name)=>{
        let data = this.state.data;
        data[name] = event.target.value;
        this.setState({
            data
        })
    }

    changeCompany=(event)=>{
        let data = this.state.data;
        data.company = event.target.value;
        this.setState({
            data
        })
    }

    changeAddress=(event)=>{
        let data = this.state.data;
        data.address = event.target.value;
        this.setState({
            data
        })
    }

    getIdName=(type)=>{
        let idArr = this.state.idArr;
        let idname = '';

        for(var i=0;i<idArr.length;i++){
            if(idArr[i].type === type){
                idname = idArr[i].name;

                this.setState({
                    idname
                })
            }
        }
    }

    changeMobile=()=>{

        if(!this.state.password){
            this.setState({
                msg:'请先输入登录密码！',
                showMsg:true
            })
            return false;
        }

        if(!this.state.phone){
            this.setState({
                msg:'请先输入手机号！',
                showMsg:true
            })
            return false;
        }

        var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;

        if (!myreg.test(this.state.phone)) {
            
            this.setState({
                msg:'请输入准确的手机号码！',
                showMsg:true
            })
            return false;
        }

        if(!this.state.code){
            this.setState({
                msg:'请先输入验证码！',
                showMsg:true
            })
            return false;
        }

        


        let param = {
            mobile:this.state.data.mobile,
            password:this.state.password,
            newmobile:this.state.phone,
            captcha:this.state.code,
            token:get('token'),
            type:get('type')?get('type'):0,
            content:get('city')?get('city'):get('mechanism'),
        }

        getApiChangeMobile(param)
        .then( req =>{
            if(req.data.code === 1){
                this.setState({
                    success:true
                })

                this.getUserInfo();
            }else{
                this.setState({
                    showMsg:true,
                    msg:req.data.msg,
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    gotoSend=()=>{

        if(!this.state.phone){
            this.setState({
                msg:'请先输入手机号！',
                showMsg:true
            })
            return false;
        }

        var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;

        if (!myreg.test(this.state.phone)) {
            this.setState({
                msg:'请输入准确的手机号码！',
                showMsg:true
            })
            return false;
        }

        let event = "";

        if(this.state.ischangePas){
            event = "resetpwd"
        }else{
            event = "changemobile"
        }


        let param = {
            mobile:this.state.phone,
            event
        }

        getApiSend(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){
                this.setState({
                    isSend:true
                })
                this.countDown();
            }else{
                this.setState({
                    msg:req.data.msg,
                    showMsg:true
                })
            }
        }).catch( err =>{
            console.error(err);
        })


        
        
    }

    render() {
        return (
            <div className="user">
                <div className="user_info">
                    <h1>个人资料</h1>
                    <div className="item">
                        <p>头像</p>
                        <div className="ia">
                            <img className="avatar" alt="" src={this.state.avatar?this.state.avatar:'assets/imgs/avatar.png'} />
                        </div>
                    </div>
                    <div className="btn bbox">
                        <button className="btn1">更换头像</button>
                        <input value="" className='load' onChange={(ev)=>{this.gotoLoadImg(ev)}} type="file" accept="image/*" id="inputFile"  />
                    </div>

                    <div className="item">
                        <p>用户名</p>
                        <input className="ipt" placeholder="请输入用户名" type="text" value={this.state.data.nickname} onChange={(ev)=>{this.changeDataStr(ev,'nickname')}} />
                    </div>
                    <div className="item">
                        <p>姓名</p>
                        <input className="ipt" placeholder="请输入姓名" type="text" value={this.state.data.truename} onChange={(ev)=>{this.changeDataStr(ev,'truename')}} />
                    </div>
                    <div className="item">
                        <p>学号</p>
                        <input className="ipt" placeholder="请输入学号" type="text" value={this.state.data.s_number} onChange={(ev)=>{this.changeDataStr(ev,'s_number')}} />
                    </div>
                    <div className="item">
                        <p>单位</p>
                        <div className="ipt" onClick={()=>{this.setState({showCompany:!this.state.showCompany})}}>
                            <h2 className={this.state.data.company?"":"i_none"}>{this.state.data.company?this.state.data.company:"请选择单位"}</h2>
                            <img alt="" src="assets/imgs/xialaxuanze.png" />
                            <div className="sels" hidden={!this.state.showCompany} onMouseLeave={()=>{this.setState({showCompany:false})}}>
                                {
                                    this.state.companyList.map((item,index)=>{
                                        return <h4 key={index} className={this.state.data.company === item.company_name?'hover':''} onClick={()=>{
                                            let data = this.state.data;
                                            data.company = item.company_name;
                                            this.setState({company:item.company_name})
                                        }}>{item.company_name}</h4>
                                    })
                                }
                            </div>
                        </div>
                        {/* <input className="ipt" placeholder="请输入单位" type="text" value={this.state.data.company} onChange={(ev)=>{this.changeDataStr(ev,'company')}} /> */}
                    </div>
                    <div className="item">
                        <p>邮箱</p>
                        <input className="ipt" placeholder="请输入邮箱" type="text" value={this.state.data.email} onChange={(ev)=>{this.changeDataStr(ev,'email')}} />
                    </div>
                  

                    <div className="btn">
                        <button className="btn2" onClick={()=>{this.gotoUpdateInfo()}}>更新个人信息</button>
                    </div>
                </div>


                <div className="user_set">
                    <div className="safe">
                        <h1>安全设置</h1>
                        <div className="item">
                            <h2>登录密码</h2>
                            <div>*******************</div>
                            <button onClick={()=>{this.setState({ischangePas:true,showMsg:false,})}}>修改</button>
                        </div>
                        <div className="item">
                            <h2>手机绑定</h2>
                            <div>{this.state.data.mobile}</div>
                            <button onClick={()=>{this.setState({ischangePhone:true,showMsg:false})}}>修改</button>
                        </div>
                    </div>
                </div>


                <div className="alert" hidden={!this.state.ischangePas}>
                    <div className="abox" hidden={this.state.success}>
                        <div className="acen">
                            <img onClick={()=>{this.gotoClose()}} className="close" alt="" src="assets/imgs/tankuangcha.png" />
                            <div className="aright">
                                <h1>修改密码</h1>
                                <div className="card">
                                    <h2>请输入手机号</h2>
                                    <input type="text" value={this.state.phone} onChange={(ev)=>{this.setState({phone:ev.target.value})}} />
                                </div>
                                <div className="card">
                                    <h2>请输入验证码</h2>
                                    <div className="card2">
                                        <input className="c2" type="text" value={this.state.code} onChange={(ev)=>{this.setState({code:ev.target.value})}} />
                                        <div className="send" onClick={()=>{this.gotoSend()}}>{this.state.isSend?this.state.countDownNum+"s 后重发":"获取验证码"}</div>
                                    </div>
                                </div>
                                <div className="card">
                                    <h2>请输入新密码</h2>
                                    <input type="password" value={this.state.password} onChange={(ev)=>{this.setState({password:ev.target.value})}} />
                                </div>
                                <div className="card">
                                    <h2>确认密码</h2>
                                    <input type="password" value={this.state.confirmpassword} onChange={(ev)=>{this.setState({confirmpassword:ev.target.value})}} />
                                </div>
                                <div className="amsg">
                                    <p hidden={!this.state.showMsg}>{this.state.msg}</p>
                                </div>
                                <button onClick={()=>{this.gotoUpdatePsw()}}>更新密码</button>
                            </div>
                        </div>
                    </div>

                    <div className="a_success" hidden={!this.state.success}>
                        <div className="acen">
                            <img alt="" src="assets/imgs/chenggong.png" />
                        </div>
                        <h2>密码修改成功！</h2>
                        <p>请您用新的密码重新登录系统，感谢您的理解！</p>
                        <div className="acen">
                            <button onClick={()=>{this.gotoPage('/login')}}>好的，去登录</button>
                        </div>
                    </div>
                </div>

                <div className="alert" hidden={!this.state.ischangePhone}>
                    <div className="abox" hidden={this.state.success}>
                        <div className="acen">
                            <img onClick={()=>{this.gotoClose()}} className="close" alt="" src="assets/imgs/tankuangcha.png" />
                            <div className="aright">
                                <h1>修改绑定手机</h1>
                                <div className="card">
                                    <h2>旧手机号码</h2>
                                    <div className="phone">{this.state.data.mobile}</div>
                                </div>
                                <div className="card">
                                    <h2>请输入登录密码</h2>
                                    <input type="password" value={this.state.password} onChange={(ev)=>{this.setState({password:ev.target.value})}} />
                                </div>
                                <div className="card">
                                    <h2>请输入新手机号码</h2>
                                    <input type="text" value={this.state.phone} onChange={(ev)=>{this.setState({phone:ev.target.value})}} />
                                </div>
                                <div className="card">
                                    <h2>请输入验证码</h2>
                                    <div className="card2">
                                        <input className="c2" type="text" value={this.state.code} onChange={(ev)=>{this.setState({code:ev.target.value})}} />
                                        <div className="send" onClick={()=>{this.gotoSend()}}>{this.state.isSend?this.state.countDownNum+"s 后重发":"获取验证码"}</div>
                                    </div>
                                </div>
                                <div className="amsg">
                                    <p hidden={!this.state.showMsg}>{this.state.msg}</p>
                                </div>
                                <button onClick={()=>{this.changeMobile()}}>修改手机号</button>
                            </div>
                        </div>
                    </div>

                    <div className="a_success" hidden={!this.state.success}>
                        <div className="acen">
                            <img alt="" src="assets/imgs/chenggong.png" />
                        </div>
                        <h2>手机号修改成功！</h2>
                        <p>您的新手机账号已同步更新</p>
                        <p>旧手机账号已无法使用！</p>
                        <div className="acen">
                            <button onClick={()=>{this.gotoClose()}}>好的</button>
                        </div>
                    </div>
                </div>

                <div className="alert" hidden={!this.state.showVipRule}>
                    <div className="a_rule">
                        <img alt="" src="assets/imgs/huiyuanguizebg.png" />
                        <div className="acen">
                            <div className="atext">
                                <div className="cont" dangerouslySetInnerHTML={{
                                    __html: this.state.rule
                                }}></div>
                            </div>
                        </div>
                        <div className="acen">
                            <button onClick={()=>{this.setState({showVipRule:false})}}>我了解清楚啦～</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}


const mapStateToProps = state => {

  
    return {
      info: state.info,
    }
  };


export default connect(mapStateToProps)(user);